package com.wtwd.device.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.AppSportRecordMapper;
import com.wtwd.device.model.entity.*;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.AppSportRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/08/31
 * @description
 */
@Service
public class AppSportRecordServiceImpl implements AppSportRecordService {


    @Autowired
    private AppSportRecordMapper appSportRecordMapper;
    @Value("${file.http}")
    private String fileHttp;
    @Value("${sport.location.file}")
    private String sportLocationFile;
    @Value("${file.path}")
    private String filePath;


    @Override
    public RespEntity<SportModeInfo> getSportRecordListByDeviceId(Long deviceId) {
        List<SportModeInfo> sportRecords = appSportRecordMapper.getSportRecordListByDeviceId(deviceId);
        //数据转化
        if (sportRecords != null && sportRecords.size() > 0) {
            sportRecords.stream().forEach(sportRecord -> {
                List<HeartData> heartData = JSONArray.parseArray(sportRecord.getHeartData(), HeartData.class);
                List<ElevationData> elevationData = JSONArray.parseArray(sportRecord.getElevationData(), ElevationData.class);
                List<PaceData> paceData = JSONArray.parseArray(sportRecord.getPaceData(), PaceData.class);
                List<FrequencyData> frequencyData = JSONArray.parseArray(sportRecord.getFrequencyData(), FrequencyData.class);
                sportRecord.setHeartDataList(heartData);
                sportRecord.setElevationDataList(elevationData);
                sportRecord.setPaceDataList(paceData);
                sportRecord.setFrequencyDataList(frequencyData);
            });
        }
        return new RespEntity(RespCode.SUCCESS, sportRecords);
    }

    @Override
    public RespEntity addSportRecord(SportModeInfo sportRecord) {
        //将添加的心率，步频等转化为json串存储
        sportRecord.setPaceData(JSONArray.toJSONString(sportRecord.getPaceDataList()));
        sportRecord.setHeartData(JSONArray.toJSONString(sportRecord.getHeartDataList()));
        sportRecord.setFrequencyData(JSONArray.toJSONString(sportRecord.getFrequencyDataList()));
        sportRecord.setElevationData(JSONArray.toJSONString(sportRecord.getElevationDataList()));
        Integer rest = appSportRecordMapper.addSportRecord(sportRecord);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAIL);
    }

    @Override
    public RespEntity<SportModeInfo> getLastSportRecordByDeviceId(Long deviceId) {
        SportModeInfo sportRecord = appSportRecordMapper.getLastSportRecord(deviceId);
        List<HeartData> heartData = JSONArray.parseArray(sportRecord.getHeartData(), HeartData.class);
        List<ElevationData> elevationData = JSONArray.parseArray(sportRecord.getElevationData(), ElevationData.class);
        List<PaceData> paceData = JSONArray.parseArray(sportRecord.getPaceData(), PaceData.class);
        List<FrequencyData> frequencyData = JSONArray.parseArray(sportRecord.getFrequencyData(), FrequencyData.class);
        sportRecord.setHeartDataList(heartData);
        sportRecord.setElevationDataList(elevationData);
        sportRecord.setPaceDataList(paceData);
        sportRecord.setFrequencyDataList(frequencyData);
        return new RespEntity(RespCode.SUCCESS, sportRecord);
    }

    @Override
    public Integer clearSportRecordByDate(String date) {
        //1.删除过期运动记录
        Integer rest = appSportRecordMapper.clearSportRecordByDate(date);
        //2.删除过期运动所存储的文件
        clearOverdueFile(filePath.concat(sportLocationFile), date);
        return rest;
    }

    @Override
    public Integer deleteSportRecordByDeviceId(Long id) {
        //1.获取运动定位文件
        List<SportModeInfo> sportModeInfos = appSportRecordMapper.getSportRecordListByDeviceId(id);
        //2.清除数据库运送数据
        if (sportModeInfos != null && sportModeInfos.size() > 0) {
            List<String> locationFiles = sportModeInfos.stream().map(SportModeInfo::getLocationFile).collect(Collectors.toList());
            if (locationFiles != null && locationFiles.size() > 0) {
                List<String> filePaths = locationFiles.stream().filter(e -> StringUtils.isNotBlank(e)).collect(Collectors.toList());
                for (String path : filePaths) {
                    deleteFile(path);
                }
            }
        }
        //3.清除该用户定位文件
        return appSportRecordMapper.deleteSportRecordByDeviceId(id);
    }

    /**
     * 删除指定文件夹下，文件夹名过期的文件(文件夹以天为单位存放：2021-06-01)
     *
     * @param fileLocation(一直到父文件下的绝对路径)
     * @param date(过期时间)
     */

    public void clearOverdueFile(String fileLocation, String date) {
        try {
            File file = new File(fileLocation);
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                return;
            }
            //获取文件夹名
            for (int i = 0; i < files.length; i++) {
                String dateName = files[i].getName();
                if (dateName.compareTo(date) < 0) {//文件夹的时间，小于过期时间(过期)
                    if (files[i].exists() && files[i].isDirectory()) {
                        deleteDir(files[i]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     */
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 删除一个文件。
     *
     * @param filename
     * @throws IOException
     */

    private void deleteFile(String filename) {
        try {
            String filePath = filename;
            File myDelFile = new File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
        }
    }


}
